package v1

import (
	"log"
	"net/http"
	"strconv"

	"gitee.com/daonna/collab-manage-system/service"

	"github.com/gin-gonic/gin"
)

// ListConversations 获取用户的所有会话
func ListConversations(c *gin.Context) {
	// 获取当前用户ID
	userID := c.GetUint("user_id")

	// 获取会话类型参数(可选)
	conversationType := c.Query("type") // 可以是 "all", "group", "private"

	// 调用服务层获取会话列表
	conversations, err := service.ListConversations(c, uint(userID), conversationType)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取会话列表失败: " + err.Error(),
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "成功",
		"data":    conversations,
	})
}

// GetConversation 获取单个会话详情
func GetConversation(c *gin.Context) {
	// 获取会话ID参数
	id := c.Param("id")
	conversationID, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的会话ID",
			"data":    nil,
		})
		return
	}

	// 获取当前用户ID
	userID := c.GetUint("user_id")

	// 调用服务层获取会话详情
	conversation, err := service.GetConversation(c, conversationID, uint(userID))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取会话详情失败: " + err.Error(),
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "成功",
		"data":    conversation,
	})
}

// CreateConversation 创建新会话（单聊或群聊）
func CreateConversation(c *gin.Context) {
	// 获取当前用户ID
	userID := c.GetUint("user_id")

	// 解析请求参数
	var req struct {
		Type        string  `json:"type"`        // "group" 或 "private"
		Name        string  `json:"name"`        // 群聊名称(群聊必填)
		Description string  `json:"description"` // 群聊描述(可选)
		AvatarURL   string  `json:"avatar_url"`  // 群聊头像(可选)
		MemberIDs   []int64 `json:"member_ids"`  // 成员ID列表(必填，至少一个)
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
			"data":    nil,
		})
		return
	}

	// 参数校验
	if len(req.MemberIDs) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "成员列表不能为空",
			"data":    nil,
		})
		return
	}

	if req.Type == "group" && req.Name == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "群聊名称不能为空",
			"data":    nil,
		})
		return
	}

	// 调用不同的服务创建会话
	var result interface{}
	var err error

	if req.Type == "private" {
		// 对于单聊，只需要一个对方用户ID
		if len(req.MemberIDs) != 1 {
			c.JSON(http.StatusBadRequest, gin.H{
				"code":    400,
				"message": "单聊只能指定一个对方用户",
				"data":    nil,
			})
			return
		}

		peerUserID := req.MemberIDs[0]
		result, err = service.CreatePrivateChat(c, uint(userID), uint(peerUserID))
	} else if req.Type == "group" {
		// 为群聊添加创建者
		memberIDs := make([]uint, 0, len(req.MemberIDs)+1)
		memberIDs = append(memberIDs, uint(userID)) // 添加创建者

		// 转换其他成员ID
		for _, id := range req.MemberIDs {
			memberIDs = append(memberIDs, uint(id))
		}

		result, err = service.CreateGroupChat(c, uint(userID), req.Name, req.Description, req.AvatarURL, memberIDs)
	} else {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的会话类型，必须是 'private' 或 'group'",
			"data":    nil,
		})
		return
	}

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "创建会话失败: " + err.Error(),
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "成功创建会话",
		"data":    result,
	})
}

// UpdateConversation 更新会话信息（主要用于群聊）
func UpdateConversation(c *gin.Context) {
	// 获取会话ID
	id := c.Param("id")
	conversationID, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的会话ID",
			"data":    nil,
		})
		return
	}

	// 获取当前用户ID
	userID := c.GetUint("user_id")

	// 解析请求参数
	var req struct {
		Name        string `json:"name,omitempty"`        // 群聊名称
		Description string `json:"description,omitempty"` // 群聊描述
		AvatarURL   string `json:"avatar_url,omitempty"`  // 群聊头像
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
			"data":    nil,
		})
		return
	}

	// 调用服务层更新会话
	err = service.UpdateConversation(c, conversationID, uint(userID), req.Name, req.Description, req.AvatarURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "更新会话失败: " + err.Error(),
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "成功更新会话",
		"data":    nil,
	})
}

// DeleteConversation 删除会话
func DeleteConversation(c *gin.Context) {
	// 获取会话ID
	id := c.Param("id")
	conversationID, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的会话ID",
			"data":    nil,
		})
		return
	}

	// 获取当前用户ID
	userID := c.GetUint("user_id")

	// 调用服务层删除会话
	err = service.DeleteConversation(c, conversationID, uint(userID))
	if err != nil {
		log.Printf("删除会话失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "删除会话失败: " + err.Error(),
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "成功删除会话",
		"data":    nil,
	})
}
